package com.baizhi.service;

import com.baizhi.dao.AdminDao;
import com.baizhi.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminDao adminDao;
    @Autowired
    private RedisTemplate redisTemplate;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Map<String, Object> login(Admin admin, HttpServletRequest request) {
        HashMap<String,Object> map = new HashMap<>();
        Admin admin1 = adminDao.queryByName(admin.getUsername());
        if(admin1!=null){
            //用户名存在
            if(admin1.getPassword().equals(admin.getPassword())){
                //登陆成功
                System.out.println("登陆成功");
                map.put("state","success");
                map.put("username",admin1.getUsername());

                redisTemplate.setKeySerializer(new StringRedisSerializer());
                String id = request.getSession(true).getId();
                ValueOperations valueOperations = redisTemplate.opsForValue();
                valueOperations.set(id,admin,10, TimeUnit.MINUTES);
                //StringRedisTemplate ：在存储redis中值的时候 存储的是java中的String类型
                //RedisTemplate:在存储redis中值的时候        存储的是java中的对象类型
                //  key        value
                //  String     string
                //sessionid    admin

                map.put("token",id);
            }else{
                //密码错误
                System.out.println("密码错误");
                map.put("state","false");
                map.put("msg","密码错误");
            }
        }else{
            System.out.println("用户名不存在");
            map.put("state","false");
            map.put("msg","用户名不存在");
        }
        return map;
        //42342366789797987
    }
}
